############################################
###### Replication Code for Figure A7 ######
########### January 9th, 2025 ##############
############################################

rm(list=ls())

### Script produces Figure A7 and saves it in the `/figures` folder


######## Load Data
library(fixest)
library(modelsummary)
library(dplyr)
library(ggplot2)
df <- readRDS("data/workfile.rds")

#### Figure A7

###### Treatments effects by condition
df <- df %>% 
  group_by(dem_country_code) %>% 
  mutate(trust_in_opposing_parties2 = scale(trust_in_opposing_parties))
df$trust_in_opposing_parties <- scale(df$trust_in_opposing_parties)


countries <- unique(df$dem_country_code)
country_all <- data.frame()

for(i_country in countries){
  coef_df <- data.frame()
  trust_no_cov <- feols(trust_in_opposing_parties ~ treated_econ + treated_culture, df %>% 
                          filter(dem_country_code == i_country), se = "iid") %>% 
    summary()
  trust_cov_adj <- feols(trust_in_opposing_parties ~ treated_econ + treated_culture + 
                           mean_outparty_feeling + high_pol_interest , df %>% 
                           filter(dem_country_code == i_country), se = "iid") %>% 
    summary()
  
  coef_df <- data.frame(coef = c(trust_no_cov$coefficients[2:3], trust_cov_adj$coefficients[2:3]), 
                        se = c(trust_no_cov$se[2:3], trust_cov_adj$se[2:3]),
                        name = rep(c("Economic issues \n condition", "Cultural issues \n condition"), times = 2),
                        var = rep(c("No covariates", "Covariate adj."), each = 2), 
                        country = i_country)
  
  country_all <- rbind.data.frame(country_all, coef_df)
}


pd <- position_dodge(0.5)

#coef_df <- coef_df

ggplot(country_all, aes(x = name,y = coef, color = var)) + 
  #ylim(c(-0.15, 0.05)) +
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(aes( ymin = coef - se*1.959964, ymax = coef + se*1.959964), width = 0, position = pd) + 
  geom_errorbar(aes( ymin = coef - se*1.644854, ymax = coef + se*1.644854), width = 0, position = pd, linewidth = 1.5) + 
  geom_hline(yintercept = 0, color = "red", linetype = "dashed") +
  scale_colour_manual(values = c("black", "grey", "darkorange")) + 
  xlab("") + 
  ylab("Treatment effect on out-partisan trust") +
  coord_flip() +
  facet_wrap(~ country, nrow = 5) + 
  theme_bw() + 
  guides(color=guide_legend(title=""))

ggsave("figures/FigA7_agg_treatments_countries.pdf", 
       height = 10, width = 8)
